var userData={'iknowTime':[], 'iknowItem':[], 'dictationTime':[], 'dictationItem':[]};
var today, allData=[[],[],[],[]], mLabel=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], ajax=[], active=[1,1];

function init() {
    var args = _args(), mid = args.mid;
    if(args.view=='canvas') period=56;
    else period=28;
    prefs = new _IG_Prefs(mid);
    tabs = new _IG_Tabs(mid);
    userName = prefs.getArray("users").slice(0,5);
    msg = new _IG_MiniMessage(mid, _gel("error_msg"));
    tabs.addTab("<a class='tab_menu'>iknow!:Time<a>", "one_id", tabCallback);
    tabs.addTab("<a class='tab_menu'>iknow!:Item</a>", "two_id", tabCallback);
    tabs.addTab("<a class='tab_menu'>Dict:Time</a>", "three_id", tabCallback);
    tabs.addTab("<a class='tab_menu'>Dict:Item</a>", "four_id", tabCallback);
}

function loadTab(app, index) {
    var indexTime = app+"Time", indexItem = app+"Item", error_msg="", id=(index<2)?0:1;
    
    $("#placeholder"+index).css("background", "url(http://iknow-rivals.googlecode.com/svn/trunk/image/loading.gif) no-repeat 50% 50%");
    
    for(var u=0; u<userName.length; u++) {
	active[id]<<=1;
	userData[indexTime][u] = [{label:userName[u], data:[], color:u, lines:'', points:''},0];
	userData[indexItem][u] = [{label:userName[u], data:[], color:u, lines:'', points:''},0];
	
	ajax[u] = $.ajax({
	    dataType: "jsonp",
	    url: "http://api.iknow.co.jp/users/"+userName[u]+"/study_results/"+app+".json?per_page="+period+"&callback=?",
	    success: function(data, status) {
		var user, ldTime, ldItem, name = this.url.match(/.+\/users\/([^\/]+)\/.+/);
		active[id]>>=1;
		name.shift();
		for(user in userName) {
		    if(userData[indexTime][user][0].label == name[0]) {
			ldTime = userData[indexTime][user];
			ldItem = userData[indexItem][user];
			break;
		    }
		}
		if('error' in data) {
		    userData[indexTime].splice(user, 1);
		    userData[indexItem].splice(user, 1);
		    userName.splice(user,1);
		    error_msg += "user name ["+name[0]+"] is invalid.<br>";
		} else {
		    today = data['today'];
		    var j=0, results = data['study_results'];
		    for(var i=0; i<period; i++) {
			var t = results[j]['timestamp'];
			if(t+86400*i==today) {
			    ldTime[0].data.push([period-i, results[j]['seconds']/60]);
			    ldItem[0].data.push([period-i, results[j]['seen']]);
			    ldTime[1]+=results[j]['seconds'];
			    ldItem[1]+=results[j]['seen'];
			    j++;
			} else {
			    ldTime[0].data.push([period-i, 0.0]);
			    ldItem[0].data.push([period-i, 0]);
			}
		    }
		}
		if(active[id]==1) {
		    userData[indexTime].sort(function(a,b){return a[1]-b[1]}).reverse();
		    userData[indexItem].sort(function(a,b){return a[1]-b[1]}).reverse();
		    for(var i=0; i<userName.length; i++) {
			if(id==0) {
			    allData[0][i]=userData[indexTime][i][0];
			    allData[1][i]=userData[indexItem][i][0];
			} else {
			    allData[2][i]=userData[indexTime][i][0];
			    allData[3][i]=userData[indexItem][i][0];
			}
		    }
		    plotLineChart(allData[index], index);
		    //plotBarChart(allData[index], index);
                    $("#placeholder"+index).css("background", "");
		    if(error_msg) msg.createStaticMessage(error_msg);
		    _IG_AdjustIFrameHeight();
		}
	    },
	    error: function(data, status, e) {
		alert("error");
	    },
	    notmodified: function(data, status) {
		alert("notmodified");
	    },
	    timeout: function(data, status) {
		alert("timeout");
	    },
	    parserror: function(data, status) {
		alert("parserror");
	    }
	});
    }
}

function showTooltip(x, y, contents) {
    $('<div id="tooltip">' + contents + '</div>').css( {
        position: 'absolute',
        display: 'none',
        top: y-2,
        left: x-25,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#444',
        opacity: 0.80,
	'font-size': '8pt',
	color: '#fff',
	'z-index':9
    }).appendTo("body").fadeIn(200);
}

function xTickFormatter(n) {
    var t, m , d;
    t= new Date((today-(period-n)*86400)*1000);
    m=t.getMonth();
    d=t.getDate();
    delete t;
    return mLabel[m]+"."+d;
}

function userLabelFormatter(s) {
    return '<a class="legend" target="_blank" href="http://www.iknow.co.jp/users/'+s+'">'+s+'</a>';
}

function plotLineChart(plotData, index) {
    var pHolder=$("#placeholder"+index), unit=index%2?'items':'min', t=[], plotOption;

    for(var i=0; i<plotData.length; i++) {
	plotData[i].lines = {show:true,lineWidth:1};
	plotData[i].points = {show:true,fill:true,fillColor:'#fff',lineWidth:2,radius:2};
    }
    
    for(i=0; i<parseInt(period/7); i++){t[i]=7*(i+1)}
    plotOption = { legend:{position:'nw', backgroundOpacity:0.64, labelFormatter:userLabelFormatter},
		   grid:{ hoverable: true, clickable: true, mouseActiveRadius:6, borderWidth:1},
		   xaxis:{ min: 1, max: period+1, ticks:t, mode:"xy", tickFormatter:xTickFormatter},
		   yaxis:{ min:0, max: null, autoscaleMargin:0.1},
		   selection:{ mode: "xy"}
		 };
    $.plot(pHolder.css("background", ""), plotData, plotOption);
    var previousPoint = null;
    pHolder.bind("plothover", function (event, pos, item) {
	if(item) {
	    if(previousPoint != item.datapoint) {
                previousPoint = item.datapoint;
                $("#tooltip").remove();
                var y=index%2?item.datapoint[1]:item.datapoint[1].toFixed(2);
                showTooltip(item.pageX, item.pageY-40,
                            item.series.label+"<br><b>"+y+"</b> "+unit);
            }
        }
        else {
            $("#tooltip").remove();
            previousPoint = null;            
        }
	
    });
}

function plotBarChart(plotData, index) {
    var placeHolder="#placeholder"+index, container="#container"+index;

    for(var i=0; i<plotData.length; i++) {
	plotData[i].bars = {show:true,barWidth:0.2};
	for(var j=0; j<plotData[i].data.length; j++) {
	    plotData[i].data[j][0] = plotData[i].data[j][0]-1+(0.2*i);
	}
    }
    
    $.plot($(placeHolder), plotData, {legend:{position:'nw', container:$(container),noColumns:4},grid:{ hoverable: true, clickable: true, mouseActiveRadius:6, borderWidth:1},xaxis:{max:7}});
	   
    /*
    $.plot($(placeHolder), [{label:userName[0],data:[[0.0,3],[1.0,8],[2.0,5],[3.0,13],[4.0,3],[5.0,10],[6.0,2]], bars:{show:true,barWidth:0.2}},
			    {label:userName[1],data:[[0.2,3],[1.2,8],[2.2,5],[3.2,13],[4.2,3],[5.2,10],[6.2,2]], bars:{show:true,barWidth:0.2}},
			    {label:userName[2],data:[[0.4,3],[1.4,8],[2.4,5],[3.4,13],[4.4,3],[5.4,10],[6.4,2]], bars:{show:true,barWidth:0.2}},
			    {label:userName[3],data:[[0.6,3],[1.6,8],[2.6,5],[3.6,13],[4.6,3],[5.6,10],[6.6,2]], bars:{show:true,barWidth:0.2}}],
	   {legend:{position:'nw', container:$(container),noColumns:4},grid:{ hoverable: true, clickable: true, mouseActiveRadius:6, borderWidth:1},xaxis:{max:7}});
*/
}

function tabCallback(tabId) {
    var i=tabs.getSelectedTab().getIndex();
    var id=(i<2)?0:1;
    if(allData[i].length==0 && active[id]==1) {
	if(id==0)
	    loadTab("iknow", i);
	else
	    loadTab("dictation", i);
    } else {
	plotLineChart(allData[i], i);
    }
}

_IG_RegisterOnloadHandler(init);